package com.tuwer.interceptor;

import com.tuwer.annotation.Log;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author 土味儿
 * Date 2022/1/26
 * @version 1.0
 */
@Slf4j
public class LogInterceptor implements HandlerInterceptor {
    /**
     * 本地线程存储类
     */
    private static final ThreadLocal threadLocal = new ThreadLocal();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            // 得到方法的注解类
            Log methodAnnotation = handlerMethod.getMethodAnnotation(Log.class);

            if (methodAnnotation != null) {
                // 当前时间
                long start = System.currentTimeMillis();
                threadLocal.set(start);
            }

            return true;
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        if(handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            // 方法
            Method method = handlerMethod.getMethod();
            // 得到方法的注解类
            Log methodAnnotation = handlerMethod.getMethodAnnotation(Log.class);
            if (methodAnnotation != null) {
                // 请求路径
                String requestURI = request.getRequestURI();

                // 方法全名
                String globalMethodName = method.getDeclaringClass().getName() + "#" + method.getName();

                // 注解描述信息
                String desc = methodAnnotation.desc();

                // 执行时间
                long end = System.currentTimeMillis();
                long start = (long) threadLocal.get();
                long dur = end - start;
                threadLocal.remove();

                // 输出日志
                log.info("请求路径: {}，请求方法: {}，描述信息: {}，总计耗时: {}",requestURI,globalMethodName,desc,dur);
            }
        }

    }
}
